<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="productName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="productKeywords">
        <el-input
          v-model="queryParams.productKeywords"
          placeholder="请输入商品关键字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-house" @click="handleViewWarehouse">查看仓库</el-button>
      </el-col>
      <!-- 添加状态提示 -->
      <el-alert
          v-if="isViewingWarehouse"
          title="当前查看的是下架商品（仓库中的商品）"
          type="info"
          show-icon
          closable
          @close="handleCloseWarehouseView"
          class="mb8"
      />
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品编号" align="center" prop="productCode" />
      <el-table-column label="商品售价" align="center" prop="productPrice" />
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column label="品牌logo" align="center" prop="logo">
        <template #default="scope">
          <img :src="scope.row.logo" width="50" height="50" v-if="scope.row.logo" />
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="商品图片" align="center" prop="allImages">
        <template #default="scope">
          <img :src="scope.row.allImages" width="50" height="50" v-if="scope.row.allImages" />
        </template>
      </el-table-column>
      <el-table-column label="商品关键字" align="center" prop="productKeywords" />
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="销量" align="center" prop="salesVolume" />
      <el-table-column label="商品排序" align="center" prop="sortOrder" />
      <el-table-column label="商品状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'warning' : 'info'"
              effect="dark"
          >
            {{ scope.row.status === 1 ? '上架' : scope.row.status === 2 ? '下架' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="是否新品" align="center" prop="isNew">
        <template #default="scope">
          <el-tag
              :type="scope.row.isNew === 1 ? 'custom-pink' : 'info'"
              effect="dark"
          >
            {{ scope.row.isNew === 1 ? '新品' : '旧品' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column label="商品详情描述" align="center" prop="description" />
      <el-table-column label="是否热门商品" align="center" prop="isHot">
        <template #default="scope">
          <el-tag
              :type="scope.row.isHot === 1 ? 'success' : scope.row.isHot === 2 ? 'warning' : 'info'"
              effect="dark"
          >
            {{ scope.row.isHot === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="服务保障" align="center" prop="serviceGuarantees" />
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['product:product:edit']"
              size="small"
          >
            修改
          </el-button>

          <el-button
              v-if="scope.row.status == 2"
              link
              type="success"
              icon="Upload"
              @click="handleChangeStatus(scope.row, 1)"
              size="small"
          >
            上架
          </el-button>

          <el-button
              v-if="scope.row.status == 1"
              link
              type="warning"
              icon="Download"
              @click="handleChangeStatus(scope.row, 2)"
              size="small"
          >
            下架
          </el-button>

          <el-button
              link
              type="info"
              icon="View"
              @click="handleView(scope.row)"
              size="small"
          >
            详情
          </el-button>

          <!-- 添加查看SKU按钮 -->
          <el-button
              link
              type="primary"
              icon="Collection"
              @click="handleViewSku(scope.row)"
              size="small"
          >
            SKU
          </el-button>

          <!-- 添加属性按钮 -->
          <el-button
              link
              type="primary"
              icon="DataLine"
              @click="handleViewAttribute(scope.row)"
              size="small"
          >
            属性
          </el-button>


          <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['product:product:remove']"
              size="small"
          >
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>


    <!-- 商品详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商品ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ detailData.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品编号">{{ detailData.productCode }}</el-descriptions-item>
        <el-descriptions-item label="商品售价">{{ detailData.productPrice }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ detailData.brandName }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ detailData.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detailData.unitName }}</el-descriptions-item>
        <el-descriptions-item label="库存数量">{{ detailData.stock }}</el-descriptions-item>
        <el-descriptions-item label="最低库存预警值">{{ detailData.minStock }}</el-descriptions-item>
        <el-descriptions-item label="商品排序">{{ detailData.sortOrder }}</el-descriptions-item>
        <el-descriptions-item label="商品状态">
          <dict-tag :options="product_status" :value="detailData.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="原价">{{ detailData.originalPrice }}</el-descriptions-item>
        <el-descriptions-item label="是否新品">
          <dict-tag :options="is_new" :value="detailData.isNew"/>
        </el-descriptions-item>
        <el-descriptions-item label="是否热门">
          <dict-tag :options="is_hot" :value="detailData.isHot"/>
        </el-descriptions-item>
        <el-descriptions-item label="销量">{{ detailData.salesVolume }}</el-descriptions-item>
        <el-descriptions-item label="浏览量">{{ detailData.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="重量">{{ detailData.weight }}</el-descriptions-item>
        <el-descriptions-item label="是否允许退款">{{ detailData.isRefund === '1' ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(detailData.startTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(detailData.endTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="服务保障">{{ detailData.serviceGuarantees }}</el-descriptions-item>
        <el-descriptions-item label="退款原因" :span="2">{{ detailData.refundCase }}</el-descriptions-item>
        <el-descriptions-item label="商品关键字" :span="2">{{ detailData.productKeywords }}</el-descriptions-item>
        <el-descriptions-item label="商品详情描述" :span="2">{{ detailData.description }}</el-descriptions-item>
        <el-descriptions-item label="品牌Logo" :span="2">
          <img v-if="detailData.logo" :src="detailData.logo" width="100" height="100" />
        </el-descriptions-item>
        <el-descriptions-item label="商品图片" :span="2">
          <img v-if="detailData.allImages" :src="detailData.allImages" width="100" height="100" />
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="onPageChange"
    />


    <!-- SKU查看对话框 -->
    <el-dialog :title="skuTitle" v-model="skuOpen" width="1200px"   style="height: 300px;" append-to-body>
      <el-table :data="skuData" border stripe>
        <el-table-column label="SKU ID" align="center" prop="id" width="80" />
        <el-table-column label="SKU编码" align="center" prop="skuCode" width="200" show-overflow-tooltip />
        <el-table-column label="规格属性" align="center" prop="specification" width="200" show-overflow-tooltip />
        <el-table-column label="销售价格" align="center" prop="salesPrice" width="100">
          <template #default="scope">
            ¥{{ scope.row.salesPrice }}
          </template>
        </el-table-column>
        <el-table-column label="促销价格" align="center" prop="promoPrice" width="100">
          <template #default="scope">
            ¥{{ scope.row.promoPrice }}
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center" prop="stock" width="80" />
        <el-table-column label="最低库存" align="center" prop="minStock" width="100" />
        <el-table-column label="重量" align="center" prop="weight" width="80">
          <template #default="scope">
            {{ scope.row.weight }}kg
          </template>
        </el-table-column>
        <el-table-column label="销量" align="center" prop="salesVolume" width="80" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="skuOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 属性查看对话框 -->
    <el-dialog :title="attributeTitle" v-model="attributeOpen" width="1000px" append-to-body>
      <el-table :data="attributeData" border stripe>
        <el-table-column label="属性ID" align="center" prop="id" width="80" />
        <el-table-column label="属性名称" align="center" prop="attributeName" show-overflow-tooltip />
        <el-table-column label="属性值" align="center" prop="attributeValue" show-overflow-tooltip />
        <el-table-column label="排序号" align="center" prop="sortOrder" width="80" />
        <el-table-column label="属性类型" align="center" prop="attributeType" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.attributeType === 0 ? 'primary' : 'success'">
              {{ scope.row.attributeType === 0 ? '商品' : '秒杀' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
          <template #default="scope">
            {{ parseTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="attributeOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>




    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="商品售价" prop="productPrice">
              <el-input v-model="form.productPrice" placeholder="请输入商品售价" />
            </el-form-item>
            <el-form-item label="品牌名称" prop="brandName">
              <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
            </el-form-item>
            <el-form-item label="品牌logo" prop="logo">
              <el-upload
                  action="/product/product/uploadImage"
                  :show-file-list="false"
                  :on-success="handleLogoUpload"
                  :before-upload="beforeUpload"
              >
                <img v-if="form.logo" :src="form.logo" width="100" height="100">
                <el-button v-else type="primary" icon="Upload">上传图片</el-button>
              </el-upload>
            </el-form-item>

            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
            </el-form-item>
            <!-- 商品图片上传 -->
            <el-form-item label="商品图片" prop="allImages">
              <el-upload
                  action="/product/product/uploadImage"
                  :show-file-list="false"
                  :on-success="handleAllImagesUpload"
                  :before-upload="beforeUpload"
              >
                <img v-if="form.allImages && form.allImages.split(',')[0]" :src="form.allImages.split(',')[0]" width="100" height="100">
                <el-button v-else type="primary" icon="Upload">上传图片</el-button>
              </el-upload>
              <!-- 显示已上传的图片缩略图 -->
              <div v-if="form.allImages" class="image-preview-list">
                <img
                    v-for="(img, index) in form.allImages.split(',')"
                    :key="index"
                    :src="img"
                    width="50"
                    height="50"
                    style="margin: 5px; border: 1px solid #ddd; border-radius: 4px;"
                />
              </div>
            </el-form-item>
            <el-form-item label="商品关键字" prop="productKeywords">
              <el-input v-model="form.productKeywords" placeholder="请输入商品关键字" />
            </el-form-item>
            <el-form-item label="单位名称" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量" prop="salesVolume">
              <el-input v-model="form.salesVolume" placeholder="请输入销量" />
            </el-form-item>
            <el-form-item label="库存数量" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入库存数量" />
            </el-form-item>
            <el-form-item label="最低库存预警值" prop="minStock">
              <el-input v-model="form.minStock" placeholder="请输入最低库存预警值" />
            </el-form-item>
            <el-form-item label="商品排序" prop="sortOrder">
              <el-input v-model="form.sortOrder" placeholder="请输入商品排序" />
            </el-form-item>
            <el-form-item label="商品状态(1:上架2下架:3:草稿)" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in product_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model="form.originalPrice" placeholder="请输入原价" />
            </el-form-item>
            <el-form-item label="是否新品" prop="isNew">
              <el-radio-group v-model="form.isNew">
                <el-radio
                  v-for="dict in is_new"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否热门商品" prop="isHot">
              <el-radio-group v-model="form.isHot">
                <el-radio
                  v-for="dict in is_hot"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="服务保障" prop="serviceGuarantees">
              <el-input v-model="form.serviceGuarantees" placeholder="请输入服务保障" />
            </el-form-item>
            <el-form-item label="是否允许退款" prop="isRefund">
              <el-radio-group v-model="form.isRefund">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品详情描述" prop="description">
              <el-input v-model="form.description" placeholder="请输入商品详情描述" type="textarea" rows="4" />
            </el-form-item>
            <el-form-item label="退款原因" prop="refundCase">
              <el-input v-model="form.refundCase" placeholder="请输入退款原因" type="textarea" rows="2" />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="datetime" placeholder="请选择开始时间" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="请选择结束时间" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
       <span class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
       </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import {
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  generateIdempotentToken,
  onSaleProduct,
  offSaleProduct,
  listProductOnSale, listProductOffSale,listProductSku,  listProductAttribute
} from "@/api/product/product"
import request from "@/utils/request.js";


const { proxy } = getCurrentInstance()
const { is_new, product_status, is_nice, is_hot } = proxy.useDict('is_new', 'product_status', 'is_nice', 'is_hot')

// 添加查看仓库相关变量
const isViewingWarehouse = ref(false);
// 添加详情相关变量
const detailOpen = ref(false)
const detailTitle = ref("")
const detailData = ref({})
const productList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 添加SKU相关变量（在现有变量后面添加）
const skuOpen = ref(false)
const skuTitle = ref("")
const skuData = ref([])
const currentProductId = ref(null)

// 添加属性相关变量
const attributeOpen = ref(false)
const attributeTitle = ref("")
const attributeData = ref([])
const currentAttributeProductId = ref(null)



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
    productKeywords: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)



// 修改查看SKU方法
function handleViewSku(row) {
  currentProductId.value = row.id
  listProductSku(row.id).then(response => {
    if (response.code === 200) {
      skuData.value = response.data || []
      skuTitle.value = `商品 "${row.productName}" 的SKU列表`
      skuOpen.value = true
    } else {
      proxy.$modal.msgError(response.msg || '获取SKU失败')
    }
  }).catch(error => {
    console.error('获取SKU失败:', error)
    proxy.$modal.msgError('获取SKU失败')
  })
}


// 添加查看属性方法
function handleViewAttribute(row) {
  currentAttributeProductId.value = row.id
  listProductAttribute(row.id).then(response => {
    if (response.code === 200) {
      attributeData.value = response.data || []
      attributeTitle.value = `商品 "${row.productName}" 的属性列表`
      attributeOpen.value = true
    } else {
      proxy.$modal.msgError(response.msg || '获取属性失败')
    }
  }).catch(error => {
    console.error('获取属性失败:', error)
    proxy.$modal.msgError('获取属性失败')
  })
}


// 查询列表
function getList() {
  console.log('Query Params:', queryParams.value);
  loading.value = true;

  // 根据视图状态选择不同的查询方法
  let requestPromise;
  if (isViewingWarehouse.value) {
    // 查看仓库（下架商品）
    requestPromise = listProductOffSale(queryParams.value);
  } else {
    // 查看上架商品
    requestPromise = listProductOnSale(queryParams.value);
  }

  requestPromise.then(response => {
    console.log('API Response:', response);
    if (response.code === 200) {
      productList.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      proxy.$modal.msgError(response.msg || '查询失败');
    }
    loading.value = false;
  }).catch(error => {
    console.error('Error fetching data:', error);
    proxy.$modal.msgError('查询数据失败');
    loading.value = false;
  });
}

// 查看仓库按钮操作
function handleViewWarehouse() {
  isViewingWarehouse.value = true;
  this.queryParams.status = 2; // 设置状态为 2（下架）
  this.getList(); // 重新获取数据
}

// 关闭仓库视图
const handleCloseWarehouseView = () => {
  isViewingWarehouse.value = false;
  // 刷新商品列表，确保显示的是上架商品
  getList();
};

// 图片上传相关方法
function beforeUpload(file) {
  const isIMAGE = file.type.indexOf('image/') !== -1
  if (!isIMAGE) {
    proxy.$modal.msgError('只能上传图片文件!')
    return false
  }
  return true
}


// 分页相关方法
function handleSizeChange(val) {
  queryParams.pageSize = val
  getList()
}

function onPageChange(val) {
  queryParams.pageNum = val
  getList()
}


// 图片上传相关方法 - 修改为支持不同字段
function handleLogoUpload(response, file, fileList) {
  if (response.code === 200) {
    form.value.logo = response.url;
    proxy.$modal.msgSuccess('Logo上传成功');
  } else {
    proxy.$modal.msgError(response.msg || 'Logo上传失败');
  }
}

function handleAllImagesUpload(response, file, fileList) {
  if (response.code === 200) {
    if (!form.value.allImages) {
      form.value.allImages = response.url;
    } else {
      // 如果已经有图片，用逗号分隔添加新图片
      form.value.allImages = form.value.allImages + ',' + response.url;
    }
    proxy.$modal.msgSuccess('商品图片上传成功');
  } else {
    proxy.$modal.msgError(response.msg || '商品图片上传失败');
  }
}




// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    productName: null,
    productCode: null,
    productPrice: null,
    brandName: null,
    logo: null,
    categoryName: null,
    allImages: null,
    productKeywords: null,
    unitName: null,
    stock: null,
    sortOrder: null,
    status: null,
    originalPrice: null,
    isNew: null,
    viewCount: null,
    isRefund: null,
    refundCase: null,
    startTime: null,
    endTime: null,
    salesVolume: null,
    weight: null,
    description: null,
    isHot: null,
    serviceGuarantees: null
  }
  proxy.resetForm("productRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  isViewingWarehouse.value = false; // 重置为查看上架商品
  this.queryParams.status = 1; // 切换回上架商品
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  isViewingWarehouse.value = false; // 重置为查看上架商品
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品"
}

// 查看详情
function handleView(row) {
  detailData.value = row
  detailTitle.value = "商品详情"
  detailOpen.value = true
}

function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getProduct(_id).then(response => {
    form.value = response.data
    form.value.categoryName = Array.isArray(form.value.categoryName) ? form.value.categoryName.join('/') : form.value.categoryName || ''
    open.value = true
    title.value = "修改商品"
  })
}


async function getIdempotentToken() {
  try {
    const response = await generateIdempotentToken();
    if (response.code === 200) {
      return response.data; // 返回令牌
    } else {
      proxy.$modal.msgError(response.msg);
      return null;
    }
  } catch (error) {
    console.error('获取幂等令牌失败:', error);
    proxy.$modal.msgError('获取幂等令牌失败');
    return null;
  }
}


/** 提交按钮 */
async function submitForm() {
  proxy.$refs["productRef"].validate(async valid => {
    if (valid) {
      const token = await getIdempotentToken();
      if (!token) {
        return;
      }

      // 处理表单数据
      const formData = { ...form.value };

      let result;
      if (formData.id != null) {
        // 修改商品
        result = await updateProduct({ ...formData, idempotentToken: token });
      } else {
        // 添加商品
        result = await addProduct({ ...formData, idempotentToken: token });
      }

      if (result.code === 200) {
        proxy.$modal.msgSuccess(formData.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      } else {
        proxy.$modal.msgError(result.msg || (formData.id ? "修改失败" : "新增失败"));
      }
    }
  });
}





/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品编号为"' + _ids + '"的数据项？').then(function() {
    return delProduct(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('product/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}



// 修改商品状态（上架/下架）
function handleChangeStatus(row) {
  const statusText = row.status === 1 ? '下架' : '上架';
  const newStatus = row.status === 1 ? 2 : 1;

  proxy.$modal.confirm(`是否确认${statusText}商品"${row.productName}"？`).then(() => {
    // 根据目标状态调用不同的API
    if (newStatus === 1) {
      // 上架
      return onSaleProduct(row.id);
    } else {
      // 下架
      return offSaleProduct(row.id);
    }
  }).then(() => {
    getList(); // 更新列表数据
    proxy.$modal.msgSuccess(`${statusText}成功`);
  }).catch(() => {});
}

getList()

</script>

<style scoped>
.app-container {
  background-color: #f5f7fa;
  padding: 20px;
}

.el-table {
  margin-top: 20px;
  font-size: 14px;
}

.el-table .cell {
  text-align: center;
  white-space: nowrap; /* 防止文字换行 */
  padding: 8px 0; /* 调整单元格内边距 */
}

.el-table th {
  background-color: #eef1f6;
  color: #606266;
  font-weight: bold;
  padding: 10px 0; /* 调整表头内边距 */
}

.el-button {
  margin-right: 10px;
  color: #000 !important; /* 强制设置文本颜色 */
  font-size: 14px !important; /* 强制设置字体大小 */
  opacity: 1 !important; /* 强制设置透明度 */
}

.el-button + .el-button {
  margin-left: 5px; /* 调整按钮间的间距 */
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--warning {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

/* 自定义粉色标签样式 */
.el-tag--custom-pink {
  background-color: #ffc0cb; /* 粉色背景 */
  border-color: #ffc0cb; /* 粉色边框 */
  color: #fff; /* 白色文字 */
}

/* 调整操作按钮间距 */
.el-table__body .el-button--small {
  margin: 2px;
  padding: 5px 8px;
}

/* 操作列中的按钮组 */
.el-table__body .el-table-column--action .el-button + .el-button {
  margin-left: 2px;
}

/* 图片预览列表 */
.image-preview-list {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

</style>

